package service

import (
	"customer/src/model"
	"fmt"
)

type CustomerService struct {
	customers   []model.Customer
	customerNum int
}

func (service *CustomerService) Add(customer model.Customer) bool {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println("err=", err)
		}
	}()
	service.customerNum++
	customer.Id = service.customerNum
	service.customers = append(service.customers, customer)

	return true
}
func (service *CustomerService) Delete(id int) bool {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println("err=", err)
		}
	}()
	for k, customer := range service.customers {
		if customer.Id == id {
			service.customers = append(service.customers[:k], service.customers[k+1:]...)

		}
	}
	return true
}
func (service *CustomerService) ForEach() {

	for k, customer := range service.customers {
		fmt.Printf("第%v位客户\n", k+1)
		fmt.Printf("id=%v,name=%v,Gender=%v,Age=%v,Phone=%v,Email=%v\n",
			customer.Id, customer.Nmae, customer.Gender, customer.Age, customer.Phone, customer.Email)
	}

}

func (service *CustomerService) UpdateView(id int) (model.Customer, int) {
	var customerTar model.Customer
	var index int
	for k, customer := range service.customers {
		if customer.Id == id {
			customerTar = customer
			index = k
		}
	}

	return customerTar, index
}

func (service *CustomerService) Update(name, gender, phone, email string, age, index int) bool {

	customer := service.customers[index]
	if name != "" {
		customer.Nmae = name
	}
	if email != "" {
		customer.Email = email
	}
	if phone != "" {
		customer.Phone = phone
	}
	if gender != "" {
		customer.Gender = gender
	}
	if age != 0 {
		customer.Age = age

	}
	service.customers[index] = customer
	return true
}
